import * as L from "leaflet";
import { WMTS } from "./WMTS";
/**
 * 有关地图基本控件用法
 */

export const commomLeaflet = {
    map: null,
    vue: null,
    option: {
        rectangle: null,
        points: [],
        pointsdata: [],
        lines: new L.polyline([]),
        tempLines: new L.polyline([], { dashArray: 5 }),
        latlngs: [],
        index: 0,
        point: [],
        layer: null,
        clickFlag: null,
        layers: [], //图层标记
        isRemoveLayers: false, //是否移除所有标记
        tmprect: null,
        layerAdd: [], //底图切换
    },
    data: {
        LeftUpperLongitude: 0, //左上经度
        LeftUpperLatitude: 0, //左上纬度
        RightLowerLongitude: 0, //右下经度
        RightLowerLatitude: 0, //右下纬度
        points: '',
    },
    // 地图选项
    options: {
        center: [32.4, 96.3], //地图的初始地理中心
        minZoom: 3,
        maxZoom: 17,
        zoom: 4,
        zoomControl: false,
        attributionControl: true,
        doubleClickZoom: false,
        crs: L.CRS.EPSG4326,
        // crs: L.CRS.EPSG3857
    },
    // 天地图之地图的配置
    skyMap1: WMTS(
        "http://t0.tianditu.gov.cn/vec_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "vec",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),
    skyMap2: WMTS(
        "http://t0.tianditu.gov.cn/cva_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "cva",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),
    // 天地图之地形的配置
    skymapTopography1: WMTS(
        "http://t0.tianditu.gov.cn/ter_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "ter",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),
    skymapTopography2: WMTS(
        "http://t0.tianditu.gov.cn/cta_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "cta",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),
    // 天地图之影像的配置
    skymapImage1: WMTS(
        "http://t0.tianditu.gov.cn/img_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "img",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),
    skymapImage2: WMTS(
        "http://t0.tianditu.gov.cn/cia_c/wmts?tk=5f62055ba4a942589b724283706c399a", {
            layer: "cia",
            tileMatrixSet: "c",
            format: "tiles",
            style: "default",
            type: "baseLayer"
        }
    ),

    // 自定义控制器
    control: function() {
        let self = this;
        // 自定义控制器
        L.Control.Legend = L.Control.extend({
            //自定义控制器的方法。右下角三个按钮的控制均在此方法内
            onAdd: function() {
                this._container = L.DomUtil.create('div', 'leaflet-draw-section');
                //创建一个图片要素
                this.label = document.createElement('div');
                this.label.setAttribute("class", 'leaflet-draw-toolbar leaflet-bar');
                // 创建绘制多边形的btn
                this.shape1 = document.createElement('a');
                this.shape1.setAttribute("class", 'leaflet-draw-draw-polygon');
                this.shape1.setAttribute("title", '绘制矩形')
                //创建绘制矩形的btn
                this.shape2 = document.createElement('a');
                this.shape2.setAttribute("class", 'leaflet-draw-draw-rectangle')
                this.shape2.setAttribute("title", '绘制矩形')
                let ref = this;
                this.shape1.onclick = () => {
                    // 阻止事件冒泡
                    self.map.off();
                    window.event ? window.event.cancelBubble = true : e.stopPropagation();
                    self.map.on('click', function(e) { self.onClick(e, self) })
                    self.map.on('mousemove', (e) => { self.onMove(e, self) })
                    self.map.on('dblclick', (e) => { self.onDoubleClick(e, self) })
                }
                this.shape2.onclick = () => {
                    self.map.off();
                    // 阻止事件冒泡
                    window.event ? window.event.cancelBubble = true : e.stopPropagation();
                    self.map.on('click', function(e) { self.onRectangleClick(e, self) })
                    self.map.on('dblclick', (e) => { self.onRectangleDoubleClick(e, self) })
                }
                // 创建取消绘制按钮
                this.cancelDraw = document.createElement('a');
                this.cancelDraw.setAttribute("class",
                    "leaflet-draw-edit-remove leaflet-draw-toolbar-button-enabled");
                this.cancelDraw.setAttribute("title", "取消绘制");
                this.cancelDraw.onclick = function(e) {
                    self.map.off();
                    // 阻止事件冒泡
                    window.event ? window.event.cancelBubble = true : e.stopPropagation();
                    self.cancelDrawFun(e, self)
                }
                this.label.appendChild(this.shape1);
                this.label.appendChild(this.shape2);
                this.label.appendChild(this.cancelDraw);
                this._container.appendChild(this.label);
                return this._container;
            },
            onRemove: function() {
                // Nothing to do here
            }
        });
        L.control.legend = function(opts) {
            return new L.Control.Legend(opts);
        }
        let legend = L.control.legend({ position: 'bottomright' });
        //添加图例
        legend.addTo(this.map);
    },
    // 初始方法
    init: function() {
        this.map = L.map("map", this.options);
        L.control.zoom({ zoomInTitle: '放大', zoomOutTitle: '缩小', position: 'bottomright' }).addTo(this.map);
        // this.map.addLayer(this.skymapTopography1);
        // this.map.addLayer(this.skymapTopography2);
        this.control();
        this.SwitchingImages()
        this.Switchmap();
        this.TerrainSwitching()
    },
    //点击画多边形
    onClick: function(e) {
        console.log(e.latlng)
        let self = arguments.length > 1 ? arguments[1] : commomLeaflet
        if (self.option.isRemoveLayers == true) {
            self.option.layers.forEach(function(val) {
                self.map.removeLayer(val);
            });
            self.option.layers = [];
            self.option.isRemoveLayers = false;
        }
        if (self.option.clickFlag) {
            window.clearTimeout(self.option.clickFlag);
            self.option.clickFlag = null;
        }
        self.option.clickFlag = setTimeout(function() {
            let bounds = [e.latlng.lat, e.latlng.lng];
            self.option.points.push([e.latlng.lat, e.latlng.lng]);
            self.option.pointsdata.push([e.latlng.lng + ' ' + e.latlng.lat]);
            self.option.lines.addLatLng(e.latlng)
            self.map.addLayer(self.option.tempLines)
            self.map.addLayer(self.option.lines)
            self.option.layer = L.circle(bounds, { radius: 500, color: '#ff0000', fillColor: '#ff0000',
                fillOpacity: 0.5 });
            self.map.addLayer(self.option.layer);
            self.option.layers.push(self.option.layer)
        }, 1);
    },
    onMove: function(e) {
        let self = arguments.length > 1 ? arguments[1] : commomLeaflet
        if (self.option.points.length > 0) {
            var ls = [self.option.points[self.option.points.length - 1],
                [e.latlng.lat, e.latlng.lng], this.option.points[0]
            ]
            self.option.tempLines.setLatLngs(ls)
            let tempLines = self.option.tempLines
            self.map.addLayer(tempLines)
            //弹出面板
            var popup = L.popup();
            popup
                .setLatLng([e.latlng.lat + 1, e.latlng.lng + 1])
                .setContent("双击结束")
                .openOn(self.map);
        }
    },
    onDoubleClick: function(e) {
        let self = arguments.length > 1 ? arguments[1] : commomLeaflet;
        if (self.option.clickFlag) {
            window.clearTimeout(self.option.clickFlag);
            self.option.clickFlag = null;
        }
        self.option.clickFlag = setTimeout(function() {
            if (self.option.points.length > 2) {
                let bounds = [e.latlng.lat, e.latlng.lng];
                self.option.points.push([e.latlng.lat, e.latlng.lng]);
                self.option.pointsdata.push(e.latlng.lng + ' ' + e.latlng.lat);
                self.option.lines.addLatLng(e.latlng)
                self.map.addLayer(self.option.tempLines)
                self.map.addLayer(self.option.lines)
                self.option.layer = L.circle(bounds, { radius: 500, color: '#ff0000',
                    fillColor: '#ff0000', fillOpacity: 0.5 });
                self.map.addLayer(self.option.layer);
                self.option.layers.push(self.option.layer)
                self.data.LeftUpperLatitude = 0;
                self.data.LeftUpperLongitude = 0;
                self.data.RightLowerLongitude = 0;
                self.data.RightLowerLatitude = 0;
                self.data.points = self.option.pointsdata;
                self.data.points.splice(self.data.points.length - 1, 1, self.data.points[0]);
                self.data.points = 'POLYGON((' + self.data.points.join(',') + '))';
                console.log(self.data.points)
                self.option.points.forEach((val) => {
                    //获取x最小值 即左上角 LeftUpperLongitude对应左上经度 LeftUpperLatitude对应左上纬度
                    // 纬度最大，经度最小
                    // e.lating[纬度，经度]
                    if (val[0] > self.data.LeftUpperLatitude) {
                        self.data.LeftUpperLatitude = val[0];
                        self.data.LeftUpperLongitude = val[1];

                    }
                    // RightLowerLongitude对应右下经度，RightLowerLatitude右下纬度
                    // 经度最大，纬度最小
                    if (val[1] > self.data.RightLowerLongitude) {
                        self.data.RightLowerLongitude = val[1];
                        self.data.RightLowerLatitude = val[0];
                    }
                })
                console.log("左上经度：" + self.data.LeftUpperLongitude)
                console.log("左上纬度：" + self.data.LeftUpperLatitude)
                console.log("右下经度：" + self.data.RightLowerLongitude)
                console.log("右下纬度：" + self.data.RightLowerLatitude)
                self.option.layer = L.polygon(self.option.points).addTo(self.map)
                self.option.layers.push(self.option.layer)
                self.option.points = []
                self.option.lines.remove()
                self.option.tempLines.remove()
                self.option.tempLines = new L.polyline([]);
                self.option.lines = new L.polyline([])
                self.option.isRemoveLayers = true;
                self.vue.$emit('tudeDate', self.data)
            } else {
                var popup = L.popup();
                popup
                    .setLatLng([e.latlng.lat + 1, e.latlng.lng + 1])
                    .setContent("请绘制多边形")
                    .openOn(self.map);
            }
        }, 1);
    },

    // 矩形
    onRectangleClick: (e) => {
        let self = commomLeaflet;
        if (self.option.isRemoveLayers == true) {
            self.option.layers.forEach(function(val) {
                self.map.removeLayer(val);
            });
            self.option.layers = [];
            self.option.isRemoveLayers = false;
        }
        if (self.option.clickFlag) {
            window.clearTimeout(self.option.clickFlag);
            self.option.clickFlag = null;
        }
        self.option.clickFlag = setTimeout(function() {
            if (self.option.tmprect != null) {
                self.option.tmprect.remove()
            }
            //左上角坐标
            self.option.latlngs[0] = [e.latlng.lat, e.latlng.lng]
            console.log(self.option.latlngs)

            //开始绘制，监听鼠标移动事件
            self.map.on('mousemove', self.onRectangleMove)
        }, 300)
    },
    onRectangleMove: (e) => {
        let self = commomLeaflet;
        self.option.latlngs[1] = [e.latlng.lat, e.latlng.lng]
        //删除临时矩形
        if (self.option.tmprect != null) {
            self.option.tmprect.remove()
        }
        //添加临时矩形
        self.option.tmprect = L.rectangle(self.option.latlngs, { dashArray: 5 }).addTo(self.map);
        //弹出面板
        var popup = L.popup();
        popup
            .setLatLng([e.latlng.lat + 1, e.latlng.lng + 1])
            .setContent("双击结束")
            .openOn(self.map);
    },
    onRectangleDoubleClick: (e) => {
        let self = commomLeaflet;
        if (self.option.clickFlag) {
            window.clearTimeout(self.option.clickFlag);
            self.option.clickFlag = null;
        }
        // self.option.clickFlag = setTimeout(function () {
        //矩形绘制完成，移除临时矩形，并停止监听鼠标移动事件
        self.option.tmprect.remove()
        self.map.off('mousemove')
        //右下角坐标
        self.option.latlngs[1] = [e.latlng.lat, e.latlng.lng];
        self.option.rectangle = L.rectangle(self.option.latlngs, {
            color: '#3388FF',
            fillOpacity: 0.2,
            weight: 2,
            background: 'red'
        })
        console.log(self.option.latlngs)

        self.data.LeftUpperLongitude = self.option.latlngs[0][1] //左上经度 经度最小值
        self.data.LeftUpperLatitude = self.option.latlngs[0][0] //左上纬度  纬度最大值
        self.data.RightLowerLongitude = self.option.latlngs[1][1] //右下经度 经度最大值
        self.data.RightLowerLatitude = self.option.latlngs[1][0] //右上纬度 纬度最小值
        self.data.points = 'POLYGON((' +
            self.data.LeftUpperLongitude + ' ' + self.data.LeftUpperLatitude + ',' +
            self.data.RightLowerLongitude + ' ' + self.data.LeftUpperLatitude + ',' +
            self.data.RightLowerLongitude + ' ' + self.data.RightLowerLatitude + ',' +
            self.data.LeftUpperLongitude + ' ' + self.data.RightLowerLatitude + ',' +
            self.data.LeftUpperLongitude + ' ' + self.data.LeftUpperLatitude +
            '))'
        console.log(self.data.points)
        // [[经度最小值,纬度最大值],[经度最大值,纬度最大值],[经度最大值,纬度最小值],
        //[经度最小值, 纬度最小值], [经度最小值, 纬度最大值]]
        console.log("左上经度：" + self.data.LeftUpperLongitude)
        console.log("左上纬度：" + self.data.LeftUpperLatitude)
        console.log("右下经度：" + self.data.RightLowerLongitude)
        console.log("右下纬度：" + self.data.RightLowerLatitude)
        self.vue.$emit('tudeDate', self.data) //data传给父元素
        self.option.layers.push(self.option.rectangle)
        self.option.rectangle.addTo(self.map);
        self.option.isRemoveLayers = true
        // }, 100)
        //调整view范围
        // self.map.fitBounds(self.option.latlngs);
    },
    //清除所有
    cancelDrawFun: (e) => {
        let self = commomLeaflet;
        if (self.option.isRemoveLayers == true) {
            self.option.layers.forEach(function(val) {
                self.map.removeLayer(val);
            });
            self.option.layers = [];
            self.option.isRemoveLayers = false;
        }
    },
    // 地图背景
    //切换成地形
    TerrainSwitching: function() {
        let self = commomLeaflet;
        self.option.layerAdd.forEach((val) => {
            self.map.removeLayer(val);
        })
        self.option.layerAdd = [];
        self.map.addLayer(self.skymapTopography1)
        self.map.addLayer(self.skymapTopography2)
        self.option.layerAdd.push(self.skymapTopography1)
        self.option.layerAdd.push(self.skymapTopography2)
    },
    // 影像切换
    SwitchingImages: function() {
        let self = commomLeaflet;
        self.option.layerAdd.forEach((val) => {
            self.map.removeLayer(val);
        })
        self.option.layerAdd = [];
        self.map.addLayer(self.skymapImage1)
        self.map.addLayer(self.skymapImage2)
        self.option.layerAdd.push(self.skymapImage1)
        self.option.layerAdd.push(self.skymapImage2)


    },
    // 地图切换
    Switchmap: function() {
        let self = commomLeaflet;
        self.option.layerAdd.forEach((val) => {
            self.map.removeLayer(val);
        })
        self.option.layerAdd = [];
        self.map.addLayer(self.skyMap1)
        self.map.addLayer(self.skyMap2)
        self.option.layerAdd.push(self.skyMap1)
        self.option.layerAdd.push(self.skyMap2)

    },
    // 根据经纬度获取地图范围
    Drawpolygon: function(geom) {
        let self = commomLeaflet;
        self.cancelDrawFun();
        if (geom) {
            let s = L.polygon(geom, { color: '#3388FF' }).addTo(self.map);
            self.option.layers.push(s);
            self.map.fitBounds(s.getBounds());
            self.option.isRemoveLayers = true;
        }
    }
}